package com.example.huhaichao.fmusic.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.example.huhaichao.fmusic.utils.ControlCode;
import com.example.huhaichao.fmusic.utils.MusicList;

/**
 * Created by huhaichao on 2017/10/13.
 * service 通过广播 控制view的状态
 */

public class MusicService extends Service {
    private static final String TAG = "MusicService";
    private CommandReceiver receiver;//接收广播：控制音乐播放
    private int status= ControlCode.STATUS_STOPPED;//播放器状态：默认停止状态
    private int number = 0;//播放的曲目：默认第一首
    private MediaPlayer player = new MediaPlayer(); // 媒体播放类
    private boolean phone = false;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        status = ControlCode.STATUS_STOPPED;
        bindCommandReceiver();
        TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        telephonyManager.listen(new MyPhoneListener(), PhoneStateListener.LISTEN_CALL_STATE);
    }
    private final class MyPhoneListener extends PhoneStateListener {

        public void onCallStateChanged(int state, String incomingNumber) {
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING:
                    if (status == ControlCode.STATUS_PLAYING) {
                        pause();
                        phone=true;
                    }
                    break;
                case TelephonyManager.CALL_STATE_IDLE:
                    if (phone == true){
                        resume();
                        phone=false;
                    }
                    break;
            }
        }
    }
    @Override
    public void onDestroy() {
        if (player != null) {
            player.release();
        }
        super.onDestroy();
    }

    /**
     * 绑定广播接收器
     * 接收 音乐控制命令 广播
     */
    private void bindCommandReceiver() {
        receiver = new CommandReceiver();
        IntentFilter filter = new IntentFilter(ControlCode.BROADCAST_MUSICSERVICE_CONTROL);
        registerReceiver(receiver, filter);
    }

    /**
     * 发送广播：提醒播放器更新UI
     */
    private void sendBroadcastOnStatusChanged(int status) {
        Intent intent = new Intent(ControlCode.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        intent.putExtra("status", status);
        if (status != ControlCode.STATUS_STOPPED) {
            intent.putExtra("time", player.getCurrentPosition());
            intent.putExtra("duration", player.getDuration());
            intent.putExtra("number", number);
            intent.putExtra("musicName", MusicList.getMusicList().get(number).getMusicName());
            intent.putExtra("musicAritis", MusicList.getMusicList().get(number).getMusicArtist());
        }
        sendBroadcast(intent);
    }

    /**
     * 播放
     */
    private void play(int number) {
        // 停止ֹ当前播放
        if (player != null && player.isPlaying()) {
            player.stop();
        }
        load(number);
        player.start();
        status = ControlCode.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(ControlCode.STATUS_PLAYING);
    }

    //加载音乐
    private void load(int number) {
        try {
            player.reset();
            player.setDataSource(MusicList.getMusicList().get(number).getMusicPath());
            player.prepare();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //注册监听器
        player.setOnCompletionListener(completionListener);
    }

    //播放结束监听器
    MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer player) {
            if (player.isLooping()) {
                replay();
            } else {
                sendBroadcastOnStatusChanged(ControlCode.STATUS_COMPLETED);//广播告诉UI 本首播放结束
            }
        }
    };

    /**
     * 暂停
     */
    private void pause() {
        if (player.isPlaying()) {
            player.pause();
            status = ControlCode.STATUS_PAUSED;
            sendBroadcastOnStatusChanged(ControlCode.STATUS_PAUSED);
        }
    }

    /**
     * 恢复播放
     */
    private void resume() {
        player.start();
        status = ControlCode.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(ControlCode.STATUS_PLAYING);
    }

    /**
     * 停止
     */
    private void stop() {
        if (status != ControlCode.STATUS_STOPPED) {
            player.stop();
            status = ControlCode.STATUS_STOPPED;
            sendBroadcastOnStatusChanged(ControlCode.STATUS_STOPPED);
        }
    }

    /**
     * 上一首
     */
    private void moveNumberToPrevious() {
        // 判断是否到达列表顶端
        if (number == 0) {
            Toast.makeText(MusicService.this,"已达到列表顶端",Toast.LENGTH_SHORT).show();
        } else {
            --number;
            play(number);
        }
    }

    /**
     * 下一首
     */
    private void moveNumberToNext() {
        // 判断是否到达列表底端
        if ((number ) == MusicList.getMusicList().size()-1) {
            Toast.makeText(MusicService.this,"已达到列表底端",Toast.LENGTH_SHORT).show();
        } else {
            ++number;
            play(number);
        }
    }

    /** 重新播放（播放完成之后）*/
    private void replay() {
        player.start();
        status = ControlCode.STATUS_PLAYING;
        sendBroadcastOnStatusChanged(ControlCode.STATUS_PLAYING);
    }

    /**
     * 拖动进度条
     */
    private void seekTo(int time) {
        player.seekTo(time);
//        sendBroadcastOnStatusChanged(ControlCode.STATUS_PLAYING);
    }

    /**
     * 接收广播
     * 音乐命令操作
     */
    class CommandReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            //获取命令
            int command = intent.getIntExtra("command", ControlCode.COMMAND_UNKNOWN);
            //执行命令
            Log.d(TAG, "onReceive: 接收到状态："+command);
            switch (command) {
                case ControlCode.COMMAND_SEEK_TO:
                    seekTo(intent.getIntExtra("time", 0));
                    Log.d(TAG, "onReceive: seekto"+intent.getIntExtra("time", 0));
                    break;
                case ControlCode.COMMAND_PLAY:
                    number = intent.getIntExtra("number", 0);
                    play(number);
                    break;
                case ControlCode.COMMAND_PREVIOUS:
                    moveNumberToPrevious();
                    break;
                case ControlCode.COMMAND_NEXT:
                    moveNumberToNext();
                    break;
                case ControlCode.COMMAND_PAUSE:
                    pause();
                    break;
                case ControlCode.COMMAND_STOP:
                    stop();
                    break;
                case ControlCode.COMMAND_RESUME:
                    resume();
                    break;
                case ControlCode.COMMAND_CHECK_IS_PLAYING:
                    if (player != null && player.isPlaying()) {
                        sendBroadcastOnStatusChanged(ControlCode.STATUS_PLAYING);
                    }
                    break;
                case ControlCode.COMMAND_UNKNOWN:
                default:
                    break;
            }
        }
    }

}
